package cn.yunyichina.provider.sb.service.impl;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.sb.constant.Constant;
import cn.yunyichina.provider.sb.dao.MedicalInvoiceNoDao;
import cn.yunyichina.provider.sb.entity.MedicalInvoiceNo;
import cn.yunyichina.provider.sb.util.Util;
import cn.yunyichina.provider.sb.vo.SbRequest;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alipay.api.response.AlipayCommerceDataSendResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by 15-AK on 2017/11/1.
 */
public class UploadMedicalInvoiceNoServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(UploadMedicalInvoiceNoServiceImpl.class);
    private final static String HOSPITAL_CODE = "szszyy";
    private MedicalInvoiceNoDao medicalInvoiceNoDao = SpringContextHandler.getBean("medicalInvoiceNoDao");

    public void executeUploadMedicalInvoiceNo() {
        try {
            MedicalInvoiceNo queryMedicalInvoiceNo = new MedicalInvoiceNo();
            queryMedicalInvoiceNo.setUploadFlag(new Short("0"));
            queryMedicalInvoiceNo.setOrgCode(HOSPITAL_CODE);
            List<MedicalInvoiceNo> medicalInvoiceNoList  = medicalInvoiceNoDao.select(queryMedicalInvoiceNo);
            if (CollectionUtils.isNotEmpty(medicalInvoiceNoList)){
                for (MedicalInvoiceNo medicalInvoiceNo : medicalInvoiceNoList) {
                    logger.info("待上传发票编号补传 medicalInvoiceNo={}", new Object[]{JsonUtils.toJsonString(medicalInvoiceNo)});
                    String encryptData = Util.encryptMedicalInvoiceNo(medicalInvoiceNo, Constant.ENCRYPT_KEY);
                    SbRequest sbRequest = new SbRequest();
                    sbRequest.setSceneCode(Constant.MEDICAL_INVOICE_SUPPLY);
                    sbRequest.setEncryptData(encryptData);
                    try {
                        AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                        logger.info("发票编号补传信息上传支付宝响应参数response={}", new Object[]{JsonUtils.toJsonString(response)});
                        if (response.isSuccess()) {
                            logger.info("发票编号补传信息上传成功");
                            medicalInvoiceNo.setUploadFlag(new Short("1"));
                        }else {
                            logger.info("发票编号补传信息上传失败");
                            medicalInvoiceNo.setExceptionMessage(response.getSubMsg());
                        }
                        medicalInvoiceNo.setUploadTimes(medicalInvoiceNo.getUploadTimes() + 1);
                        medicalInvoiceNoDao.update(medicalInvoiceNo);
                    } catch (Exception e) {
                        logger.error("发票编号补传信息上传系统异常", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("住院诊断信息上传系统异常", e);
        }
    }
}
